package cn.gov.pbc.exam.excel;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import cn.gov.pbc.exam.common.QuestionConst;
import cn.gov.pbc.exam.common.ServerResponse;
import cn.gov.pbc.exam.pojo.Answer;
import cn.gov.pbc.exam.pojo.Question;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@ToString
public class QuestionDto {
	
	private String question;
	
	private Integer type;
	
	private List<Option> optionList;
	
	public Question  assmbleQuestion() {
		Question question = new Question();
		question.setContent(this.getQuestion());
		question.setType(this.getType());
		return question;
	}
	
	public List<Answer> assmbleAnswerList(Integer questionId){
		List<Answer> answerList = new ArrayList<>();
		for(Option option : this.optionList) {
			Answer answer = new Answer();
			answer.setContent(option.getContent());
			answer.setQuestionId(questionId);
			answer.setStatus(option.getStatus());
			answer.setTitle(option.getTitle());
			answerList.add(answer);
		}
		return answerList;
	}
	
	public static ServerResponse<?> addQuestionDto(List<QuestionExcelDto> list) {
		QuestionDto dto = new QuestionDto();
		QuestionExcelDto firstRow = list.get(0);
		if(StringUtils.isBlank(firstRow.getQuestion())) {
			return ServerResponse.createByErrorMessage("问题不能为空");
		}
		if(StringUtils.isBlank(firstRow.getType())) {
			return ServerResponse.createByErrorMessage("题目类型不能为空");
		}
		QuestionConst.Type typeEnum = QuestionConst.Type.searchByValue(firstRow.getType()); 
		if(typeEnum == null) {
			return ServerResponse.createByErrorMessage("题目类型错误");
		}
		dto.setQuestion(firstRow.getQuestion().trim());
		dto.setType(typeEnum.getCode());
		List<Option> optionList = new ArrayList<>();
		dto.setOptionList(optionList);
		for(int i = 0; i < list.size(); i++) {
			QuestionExcelDto row = list.get(i);
			if(StringUtils.isBlank(row.getTitle())) {
				return ServerResponse.createByErrorMessage("选项标题不能为倾家荡产");
			}
			if(StringUtils.isBlank(row.getOptionContent())) {
				return ServerResponse.createByErrorMessage("选项内容不能为空");
			}
			if(StringUtils.isBlank(row.getStatus())) {
				return ServerResponse.createByErrorMessage("选项状态不能为空");
			}
			QuestionConst.OptionStatus optionStatus =QuestionConst.OptionStatus.searchByValue(row.getStatus()); 
			if(optionStatus == null) {
				return ServerResponse.createByErrorMessage("选项状态错误");
			}
			QuestionDto.Option option = dto.new Option();
			option.setContent(row.getOptionContent());
			option.setTitle(row.getTitle());
			option.setStatus(optionStatus.getCode());
			optionList.add(option);
		}
		return ServerResponse.createBySuccess(dto);
	}
	

	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	@ToString
	private class Option {
		private String title;
		
		private String content;
		
		private Integer status;
		
	}
}
